import hashlib
import http.client
import json

import xmltodict


#回调验证
def data_validata(request):
    #token可按照需求自定义
    token = 'myweixin'
    #timestamp，nonce，echostr，signature来自腾讯的服务器
    timestamp = request.args.get('timestamp')
    nonce = request.args.get('nonce')
    echostr = request.args.get('echostr')
    signature = request.args.get('signature')
    #进行组合排序
    list = [token, timestamp, nonce]
    list.sort()
    #进行sha1 加密
    _signature = hashlib.sha1(bytes(list[0] + list[1] + list[2],'utf-8')).hexdigest()
    print("来自腾讯的signature:" + signature)
    print("加密生成的signature:" + _signature)
    #判断是否相等
    if _signature == signature:
        return echostr
    else:
        return ''
#xml转为字典
def xmlTodict(arg):
    return xmltodict.parse(arg)


# 获取access_token
def get_accesstoken(arg1, arg2):
    conn = http.client.HTTPSConnection('api.weixin.qq.com')
    conn.request('GET', '/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (arg1, arg2))
    response = conn.getresponse()
    text = str(response.readline(), 'utf-8')
    #print(json.loads(text)["access_token"])
    return text

appid = 'wxfbdf7a2cf5375432'
secret= 'bb6195d25f0220d3571ed7d40a945834'
#
print(get_accesstoken(appid, secret))

#创建自定义菜单
def create_menu(arg):
    conn = http.client.HTTPSConnection('api.weixin.qq.com')
    conn.request('POST', '/cgi-bin/menu/create?access_token= %s'
                 % (get_accesstoken(appid,secret))['access_token'],arg)
    response = conn.getresponse()
    text = str(response.readline(),'utf-8')
    print(text)
arg = '''
 {
 "button":[
 {    
      "type":"click",
      "name":"今日歌曲",
      "key":"V1001_TODAY_MUSIC"
  },
  {
       "name":"菜单",
       "sub_button":[
       {    
           "type":"view",
           "name":"搜索",
           "url":"http://www.soso.com/"
        },
        {
             "type":"miniprogram",
             "name":"wxa",
             "url":"http://mp.weixin.qq.com",
             "appid":"wx286b93c14bbf93aa",
             "pagepath":"pages/lunar/index"
         },
        {
           "type":"click",
           "name":"赞一下我们",
           "key":"V1001_GOOD"
        }]
   }]
}              
'''.encode('utf-8')

print(create_menu(arg))

def send_server():
    conn = http.client.HTTPSConnection('api.weixin.qq.com')
    conn.request('POST', '/cgi-bin/message/custom/send?access_token=%s' % (get_accesstoken(appid,secret)['access_token']),'arg')
    response = conn.getresponse()
    text = str(response.readline(), 'utf-8')
    print(text)
openid = 'xxxxxx'
arg = ('''
{
    "touser":"%s",
    "msgtype":"text",
    "text":
    {
         "content":"Hello World"
    }
}
''' % openid).encode('utf-8')

print(send_server(arg))

def sent_temp(arg):
    conn = http.client.HTTPSConnection('api.weixin.qq.com')
    conn.request('POST', '/cgi-bin/template/api_set_industry?access_token=%s' % get_accesstoken(appid,secret)['access_token'],arg)
    response = conn.getresponse()
    text = str(response.readline(), 'utf-8')
    print(text)

tmp_id = 'xxxxx'
arg = ('''
{
"touser":"%s",
"template_id":"%s",
"url":"http://weixin.qq.com/download",  
# "miniprogram":{
#  "appid":"xiaochengxuappid12345",
#  "pagepath":"index?foo=bar"
# },          
"data":{
       "first": {
           "value":"恭喜你购买成功！",
           "color":"#173177"
       },
       "keyword1":{
           "value":"巧克力",
           "color":"#173177"
       },
       "keyword2": {
           "value":"39.8元",
           "color":"#173177"
       },
       "keyword3": {
           "value":"2014年9月22日",
           "color":"#173177"
       },
       "remark":{
           "value":"欢迎再次购买！",
           "color":"#173177"
       }
}
}
''').encode('utf-8')
print(sent_temp(arg))